package mp

import (
	"context"
	"errors"

	"ruikc.com/server/api/internal/db"
	"ruikc.com/server/api/internal/svc"
	"ruikc.com/server/api/internal/types"
	"ruikc.com/server/models"
	xb "xorm.io/builder"

	"github.com/zeromicro/go-zero/core/logx"
)

type ClassifySaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewClassifySaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ClassifySaveLogic {
	return &ClassifySaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ClassifySaveLogic) ClassifySave(req *types.ClassifyReq) (resp string, err error) {
	if req.Pid != 0 {
		pData := &models.Classify{
			Id: req.Pid,
		}
		has := db.GetData(pData)
		if !has {
			return "", errors.New("一级分类不存在或已经删除")
		}
		if pData.Pid != 0 {
			return "", errors.New("二级分类不能添加子分类")
		}
	}
	data := &models.Classify{
		Title: req.Title,
		Pid:   req.Pid,
		IsUse: req.IsUse,
	}

	if req.Id == 0 {
		db.InsertData(data)
	} else {
		_, err := l.svcCtx.Db.Cols("pid,title,is_use").Where(xb.Eq{"id": req.Id}).Update(data)
		if err != nil {
			return "", err
		}
	}

	return "操作成功", nil
}
